<template>
	<view class="chatPage">
		<headerinfo></headerinfo>

		<view class="chat">
			<view class="left">
				<view class="list">
					<image :src="userInfo.avatar" mode="aspectFill"></image>
					<view>{{nickname}}</view>
					<view class="desc">家庭：<el-dropdown v-model="familyId" @command="handleCommand">
							<span class="el-dropdown-link">
								{{familyName?familyName:'选择家庭'}}<i class="el-icon-arrow-down el-icon--right"></i>
							</span>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item :command="item.docId" v-for="(item,index) in family"
									:key="index">{{item.familyName}}</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown></view>
				</view>
				<view class="list" :class="nowliaotian.index == index?'active':''" v-if="item.username != username"
					@click="liaotian(item,index)" v-for="(item,index) in userlist" :key="index">
					<image :src="item.avatar?item.avatar:'/static/images/logo.png'" mode="aspectFill"></image>
					<view class="font">{{item.showName}}</view>
					<view class="ml-4" v-if="nowliaotian.index==index">
						<view class="font-small">是您的:{{guanxi}} </view>
						<view class="font-small text-success" @click="guanxiDia = true">点击修改关系</view>
					</view>
				</view>

			</view>

			<view class="liaotian">
				<view class="nowuser" v-if="leftNowIndex==-1">
					请选择左侧聊天对象
				</view>

				<view class="" v-else>

					<view class="box-1">
						<view class="talk-list" id="content_overflow">
							<view v-for="(item, index) in talkList" :key="index" :id="`msg-${index}`">
								<view class="item flex_col" :class="item.type == 1 ? 'push' : 'pull'">
									<image v-if="item.type == 1" :src="userInfo.avatar" mode="aspectFill" class="pic">
									</image>
									<image v-else
										:src="nowliaotian.item.avatar?nowliaotian.item.avatar:'../../static/images/robbot.png'"
										mode="aspectFill" class="pic"></image>
									<view class="content" v-if="item.type == 1">{{ item.content }}</view>

									<view class="content" v-else>
										<i class="iconfont" @click="bofang(item.voiceUrl)" v-if="item.voiceUrl"
											style="margin: 20rpx;margin-bottom: 0;">&#xe662;</i>
										<zero-markdown-view :markdown="item.content"></zero-markdown-view>

										<view class="video" v-if="item.videoUrl && item.videoUrl !='undefined'"
											style="width: 100%;">
											<video :src="item.videoUrl"
												style="width: 100%;border-radius: 20rpx;"></video>
										</view>
										<view class="copyText" @click="copy(item.content)">复制</view>
									</view>
								</view>
							</view>
						</view>


						<view class="enterbox">
							<textarea v-model="content"></textarea>

							<view class="updown"></view>
							<view class="updown">
								<el-dropdown @command="handleCommand22" class="mr-5">
									<span class="el-dropdown-link">
										回复方式：{{answerMode == 'text'?'文字':answerMode == 'voice'?'语音':'视频'}}<i
											class="el-icon-arrow-down el-icon--right"></i>
									</span>
									<el-dropdown-menu slot="dropdown">
										<el-dropdown-item command="text">文字</el-dropdown-item>
										<el-dropdown-item command="voice">语音</el-dropdown-item>
										<el-dropdown-item command="video">视频</el-dropdown-item>
									</el-dropdown-menu>
								</el-dropdown>

								<el-dropdown @command="handleChangeVoiceMode" class="mr-5" v-if="answerMode !='text' ">
									<span class="el-dropdown-link">
										声音模式：{{ useMemberSelfVoice ? '自定义声音' : '系统声音' }}<i
											class="el-icon-arrow-down el-icon--right"></i>
									</span>
									<!-- v-if="hasMemberSelfVoice" -->

									<!-- 只有有设置了自定义声音，才可以设置，否则设置也没有用，没必要设置  -->
									<!--  v-if="hasMemberSelfVoice" -->
									<el-dropdown-menu slot="dropdown">
										<el-dropdown-item command="customize">自定义声音</el-dropdown-item>
										<el-dropdown-item command="system">系统声音</el-dropdown-item>
									</el-dropdown-menu>
								</el-dropdown>

								<!--   -->
								<el-dropdown @command="handleChangeDiaogueMode" class="mr-5"
									v-if="answerMode !='text'  &&  useMemberSelfVoice ">
									<span class="el-dropdown-link">
										方言模式：{{lang ? lang : '普通话' }}<i class="el-icon-arrow-down el-icon--right"></i>
									</span>
									<!-- 只有有设置了自定义声音，才可以设置，否则设置也没有用，没必要设置 -->
									<el-dropdown-menu slot="dropdown">
										<el-dropdown-item :command="item.name" v-for="(item,index) in lanlist"
											:key="index">{{item.name}}</el-dropdown-item>
									</el-dropdown-menu>

								</el-dropdown>

								<!-- 	<view class="changeVoice" v-if="useMemberSelfVoice && answerMode !='text'  ">
									<view class="setting" @click="yuyingDia = true">
										{{ useMemberSelfVoice ? '自定义声音' : '系统声音' }} <i class="iconfont">&#xe606;</i>
									</view>
								</view> -->
								<view class="mt-4" v-if="answerMode !='text'" @click="toSetLuying">
									<view class="changeVoice" v-if="hasMemberSelfVoice">
										重新自定义声音
									</view>
									<view v-else>
										<view class="" v-if="SysParam.cosyVoiceEnabled">
											<view>
												不满意当前系统声音？
											</view>
											<view>
												点击录制<span class="font-weight-bolder text-danger">自己的声音</span>
											</view>
										</view>
									</view>
								</view>

							</view>

							<view class="send" @click="send">
								发送
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>


		<el-dialog title="选择和亲人的关系---他（她）是你的：?" :visible.sync="guanxiDia" width="40%">
			<div>
				<span>请选择：</span>
				<el-cascader :show-all-levels="false" v-model="relation" :options="options"></el-cascader>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="guanxiDia = false">取 消</el-button>
				<el-button type="primary" @click="band()">确 定</el-button>
			</span>
		</el-dialog>
	</view>
</template>

<script>
	import headerinfo from '@/components/headerinfo'
	import {
		apiBaseURL
	} from '../../common/config.js'

	import {
		fetchEventSource
	} from "@microsoft/fetch-event-source";
	export default {
		components: {
			headerinfo
		},
		data() {
			return {
				SysParam: {},
				lanlist: [],
				familyName: '',
				timer: null,
				aiavatar: '',
				content: '',
				lang: '',
				relation: [],
				options: [{
					value: '同辈',
					label: '同辈',
					children: []
				}, {
					value: '小辈',
					label: '小辈',
					children: []
				}, {
					value: '长辈',
					label: '长辈',
					children: []
				}],
				guanxiDia: false,
				guanxi: '',
				family: [],
				familyId: '',
				userlist: [],
				userInfo: uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo') : {},
				nickname: uni.getStorageSync('nickname') ? uni.getStorageSync('nickname') : '',
				leftNowIndex: -1,
				talkList: [],
				innerAudioContext: null,
				nowliaotian: {
					item: "",
					index: "",
				},
				answerMode: 'text',
				useMemberSelfVoice: false,
				hasMemberSelfVoice: false,
				requestTask: null,
				username: uni.getStorageSync('username') ? uni.getStorageSync('username') : '',
				familyMemberId: ''
			};
		},
		onLoad(e) {
			console.log('kdowqkodqwko')
			console.log(e)
			this.getRelation()
			this.getlang()
			if (e.familyId) {
				this.familyId = e.familyId
				this.leftNowIndex = -1
				this.familyMemberId = e.familyMemberId
				this.getuserList(1)

				this.getmyFamilies(1)

			} else {
				this.getmyFamilies()
			}
		},
		onShow() {
			this.getConfig()
			let cosyVoiceEnabled = this.SysParam.cosyVoiceEnabled
			if (cosyVoiceEnabled) {
				this.checkMemberVoiceExist()
			}
		},
		mounted() {
			this.innerAudioContext = uni.createInnerAudioContext();
		},
		onPageScroll(e) {
			// if (e.scrollTop < 5) {
			// 	this.getHistoryMsg();
			// }
		},
		watch: {
			// 监听当前消息列表，更新时，保持滚动条位于底部
			talkList: function scrollToBottom() {
				this.$nextTick(() => {
					var message = document.getElementById('content_overflow')
					message.scrollTop = message.scrollHeight
				})
			}
		},
		methods: {
			handleChangeDiaogueMode(lang) {
				console.log('handleChangeDiaogueMode', lang);
				this.lang = lang
			},
			getConfig() {
				this.$api.getSysParam().then(res => {
					console.log(res)
					this.SysParam = res
				})
			},
			getlang() {
				let arr = []
				this.$api.getSupportedDialect().then(res => {
					if (res && res.length > 0) {
						res.forEach(item => {
							arr.push({
								name: item,
								id: item
							})
						})
					}

					this.lanlist = arr
				})

			},
			setName() {
				this.family.forEach(item => {
					if (item.docId == this.familyId) {
						this.familyName = item.familyName
					}
				})
			},
			toSetLuying() {
				uni.navigateTo({
					url: `/pages/chat/videoset?familyMemberId=${this.familyMemberId}`
				})
				// if (this.SysParam.cosyVoiceEnabled) {
				// 	uni.navigateTo({
				// 		url: `/pages/chat/videoset?familyMemberId=${this.familyMemberId}`
				// 	})
				// } else {
				// 	uni.showModal({
				// 		title: '当前未开启-自定义语音-功能',
				// 		content: '请联系管理员开启',
				// 		showCancel: false,
				// 		cancelText: '取消',
				// 		confirmText: '确定'
				// 	});
				// }
			},
			handleCommand22(e) {
				console.log('handleCommand22', e)
				this.answerMode = e
				if (this.answerMode == 'video') {
					if (!this.SysParam.wave2lipEnabled) {
						this.answerMode = 'voice'
						uni.showModal({
							title: '当前未开启视频功能',
							content: '请联系管理员开启',
							showCancel: false,
							cancelText: '取消',
							confirmText: '确定'
						});
					}
				}
			},
			handleChangeVoiceMode(e) {
				console.log('handleChangeVoiceMode', e)
				if (e == 'customize') {
					if (this.SysParam.cosyVoiceEnabled) {
						if (this.hasMemberSelfVoice) {
							this.useMemberSelfVoice = true
						} else {
							this.useMemberSelfVoice = false
							uni.showModal({
								title: '您还没有录制自己的声音',
								content: '请录制后再进行使用',
								showCancel: false,
								cancelText: '取消',
								confirmText: '确定'
							});
						}
					} else {
						this.useMemberSelfVoice = false
						uni.showModal({
							title: '当前未开启-自定义语音-功能',
							content: '请联系管理员开启',
							showCancel: false,
							cancelText: '取消',
							confirmText: '确定'
						});
					}
				} else {
					this.useMemberSelfVoice = false
				}

			},
			// 发送信息
			send() {
				if (!this.content) {
					this.$message('请输入有效的内容')
					return;
				}

				let dataInfo = {
					content: this.content,
					type: 1,
					avatar: this.aiavatar,
					voiceUrl: '',
					answerMode: '',
					videoUrl: '',
				};

				this.talkList.push(dataInfo);


				// this.leftNowIndex = this.leftNowIndex + 2

				let dataInfo2 = {
					content: '',
					type: 2,
					avatar: this.avatar,
					voiceUrl: '',
					answerMode: '',
					videoUrl: '',
				};

				this.talkList.push(dataInfo2);

				this.getMessage(this.content)
				this.$nextTick(() => {
					// 清空内容框中的内容
					this.content = '';
					uni.pageScrollTo({
						scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
						duration: 0
					});
				});

			},
			getMessage(question) {
				const self = this

				var chatHistory = []
				if (self.talkList.length > 0) {

					let task = JSON.parse(JSON.stringify(this.talkList))
					let arr = task.splice(-12, 10)

					arr.forEach(item => {
						if (item.type == 1) {
							chatHistory.push({
								content: item.content,
								role: "user",
							})
						} else {
							chatHistory.push({
								content: item.content,
								role: "assistant",
							})
						}
					})
				}
				var query = {
					base: {
						requestId: Math.floor(Math.random() * 1000000000) + '',
						clientId: 'minghui',
						debugMore: false
					},
					dialectName: this.lang,
					answerMode: this.answerMode,
					relation: this.guanxi,
					avatar: this.nowliaotian.item.avatar,
					familyMemberId: this.nowliaotian.item.id,
					question: question,
					useMemberSelfVoice: this.useMemberSelfVoice,
					chatHistory: chatHistory
				}

				if (this.answerMode == 'text') {
					// 文本走这个


					fetchEventSource(`${apiBaseURL}/ai/streamChatWithFamilyMember`, {
						method: "POST",
						headers: {
							"Content-Type": "application/json",
							'token': uni.getStorageSync('token'),
							'Accept': 'text/event-stream'
						},
						body: JSON.stringify(query),
						onmessage(msg) {
							console.log('消息结果')
							console.log(msg)
							let contentData = msg.data
							let index = self.talkList.length - 1

							self.talkList[index].content += contentData ? contentData : ''

						},
						onclose() {},
						onerror(error) {
							console.log(error)
						},
					});
				} else {
					uni.showLoading({
						title: '思考中...'
					})
					this.$api.asyncChatWithFamilyMember(query).then(res => {
						console.log(res)
						uni.hideLoading()

						let contentData = res.answer
						let index = self.talkList.length - 1

						self.talkList[index].content += contentData ? contentData : ''

						this.timer = setInterval(() => {
							this.$api.getTaskResult({
								taskId: res.taskId
							}).then(res2 => {
								let checkedStatus = res2[0].checkedStatus
								let overdata = res2[0]
								console.log('getTaskResult',overdata);
								if (checkedStatus == 'SUCCESS' || checkedStatus == 'FAILED') {
									this.clearInterval()
									if (overdata && overdata.checkedResult && overdata
										.checkedResult.data) {
										if (this.answerMode == 'voice') {
											self.talkList[index].voiceUrl += overdata ? overdata
												.checkedResult.data : ''
											const innerAudioContext = uni
												.createInnerAudioContext();
											// 开始自动播放
											innerAudioContext.autoplay = true;
											// 设置音频地址
											innerAudioContext.src = overdata ? overdata
												.checkedResult
												.data : ''
											uni.hideLoading()
										} else {

											self.talkList[index].videoUrl += overdata ? overdata
												.checkedResult.data : ''

										}
									}
								}
							})
						}, 3000)
					})
				}
			},
			clearInterval() {
				if (this.timer) {
					clearInterval(this.timer)
					this.timer = null
					console.log('定时器已清除')
				}
			},
			band() {
				if (this.relation.length == 0) {
					return this.$message.error('请选择和亲人的关系')
				}

				let data = {
					relation: this.relation[1],
					familyMemberId: this.nowliaotian.item.id
				}
				this.$api.upsertFamilyMemberRelation(data).then(res => {
					this.$message.success('关系绑定成功')
					this.guanxiDia = false
					this.guanxi = data.relation
					this.relation = []
					this.getHistoryMsg()

				})
			},
			tochat() {

			},

			bofang(url) {

				// 停止当前播放
				this.innerAudioContext.stop();
				// 清除当前音频源
				this.innerAudioContext.src = url;
				// 播放音频
				this.innerAudioContext.play();
			},
			getHistoryMsg() {

				let item = this.nowliaotian.item
				let index = this.nowliaotian.index


				this.leftNowIndex = index

				let data = {
					familyMemberId: item.id,
					pageSize: 20
				}

				this.$api.queryMyChatConvert(data).then(res => {
					console.log('聊天记录')
					console.log(res)
					let arrData = []
					if (res.list.length > 0) {
						res.list.reverse();
						res.list.forEach(item => {
							item.forEach(item2 => {
								arrData.push(item2)
							})
						})
					}
					this.talkList = arrData;
				})
			},
			checkMemberVoiceExist() {
				let data = {
					familyMemberId: this.nowliaotian.item.id
				}
				this.$api.checkMemberVoiceExist(data).then(res => {
					console.log('是否设置了自己的声音')
					console.log(res)
					this.hasMemberSelfVoice = res.data
					if (this.hasMemberSelfVoice) {
						this.useMemberSelfVoice = true
					}
				})
			},
			getRelation() {

				this.$api.getRelation().then(res2 => {
					console.log(res2)
					let tongbei = []
					if (res2.equal.length > 0) {
						res2.equal.forEach(item => {
							tongbei.push({
								label: item,
								value: item,
							})
						})
					}

					let xiaobei = []
					if (res2.younger.length > 0) {
						res2.younger.forEach(item => {
							xiaobei.push({
								label: item,
								value: item,
							})
						})
					}

					let zhangbei = []
					if (res2.elder.length > 0) {
						res2.elder.forEach(item => {
							zhangbei.push({
								label: item,
								value: item,
							})
						})
					}

					this.options[0].children = tongbei
					this.options[1].children = xiaobei
					this.options[2].children = zhangbei


				})
			},
			liaotian(item, index) {
				let query = {
					familyMemberId: item.id
				}

				this.nowliaotian = {
					item: item,
					index: index
				}
				this.$api.queryFamilyMemberRelation(query).then(res => {
					if (this.SysParam.cosyVoiceEnabled) {
						this.checkMemberVoiceExist()
					}

					console.log('queryFamilyMemberRelation', res)
					if (res) {
						this.guanxi = res
						this.getHistoryMsg();
					} else {
						this.guanxi = ''
						this.guanxiDia = true
					}

				})




			},
			getmyFamilies(type) {
				this.$api.myFamilies().then(res => {
					console.log(res)
					this.family = res

					if (type == 1) {
						this.setName()
					}

					if (res.length > 0 && !this.familyId) {
						this.familyId = res[0].docId
						this.getuserList()
					}
				})
			},
			handleCommand(e) {
				this.familyId = e
				console.log(e)
				this.leftNowIndex = -1
				this.setName()
				this.getuserList()
			},
			getuserList(type) {
				let data = {
					familyId: this.familyId
				}
				this.$api.queryFamilyMember(data).then(res => {
					console.log('家庭列表')
					console.log(res)
					this.userlist = res.list

					if (type == 1) {
						this.userlist.forEach((item, index) => {
							if (item.id == this.familyMemberId) {
								this.liaotian(item, index)
							}
						})
					}
				})
			},
			copy(msg) {
				uni.setClipboardData({
					data: msg, // e是你要保存的内容
					success: () => {

						this.$message.success('复制成功')
					}
				})
			},
		}
	};
</script>

<style lang="scss" scoped>
	.chat {
		width: 80%;
		margin: 40rpx auto;
		border-radius: 20rpx;
		height: 80vh;
		box-shadow: 0 0 3px #ccc;
		display: flex;

		.active {
			background: #f22d2d !important;
			color: #fff;
		}


		.left {
			width: 400rpx;
			height: 100%;
			overflow-y: scroll;
			border-right: 1px solid #ececec;
			min-width: 400rpx;

			.list {
				height: 120rpx;
				position: relative;
				padding-left: 110rpx;
				display: flex;
				flex-direction: column;
				justify-content: center;
				border-bottom: 1px solid #ececec;
				cursor: pointer;



				image {
					position: absolute;
					left: 20rpx;
					top: 50%;
					transform: translateY(-50%);
					width: 70rpx;
					height: 70rpx;
					border-radius: 50%;
				}

				view {
					font-size: 30rpx;
				}

				.desc {
					font-size: 24rpx;
					color: #969393;
				}

				::v-deep .desc .el-dropdown-link {
					font-size: 24rpx !important;
				}
			}
		}

		.liaotian {
			width: 100%;

			.nowuser {
				width: 100%;
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	/* 加载数据提示 */
	.tips {
		position: fixed;
		left: 0;
		top: var(--window-top);
		width: 100%;
		z-index: 9;
		background-color: rgba(0, 0, 0, 0.15);
		height: 72rpx;
		line-height: 72rpx;
		transform: translateY(-80rpx);
		transition: transform 0.3s ease-in-out 0s;

		&.show {
			transform: translateY(0);
		}
	}

	.box-1 {
		width: 100%;
		height: auto;
		padding-bottom: 100rpx;
		box-sizing: content-box;

		/* 兼容iPhoneX */
		margin-bottom: 0;
		margin-bottom: constant(safe-area-inset-bottom);
		margin-bottom: env(safe-area-inset-bottom);
	}

	.box-2 {
		position: fixed;
		left: 50%;
		width: 540px;

		bottom: 0;
		/* #ifdef H5 */
		bottom: 98rpx;
		/* #endif */
		height: auto;
		z-index: 2;
		border-top: #e5e5e5 solid 1px;
		box-sizing: content-box;
		background-color: #f3f3f3;
		transform: translateX(-50%);
		/* 兼容iPhoneX */
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		>view {
			padding: 0 20rpx;
			height: 140rpx;
		}

		.textareas {
			background-color: #fff;
			height: 124rpx;
			padding: 10rpx 20rpx;
			border-radius: 10rpx;
			font-size: 28rpx;
			width: 650rpx;
			box-sizing: border-box;
		}

		.content {
			background-color: #fff;
			height: 124rpx;
			padding: 0 20rpx;
			border-radius: 10rpx;
			font-size: 28rpx;
		}

		.send {
			background-color: #de4849;
			color: #fff;
			height: 64rpx;
			margin-left: 20rpx;
			border-radius: 32rpx;
			padding: 0;
			width: 120rpx;
			line-height: 62rpx;

			&:active {
				background-color: #5fc496;
			}
		}
	}

	.talk-list {
		padding-bottom: 80rpx;
		height: 60vh;
		overflow-y: scroll;

		/* 消息项，基础类 */
		.item {
			padding: 20rpx 20rpx 0 20rpx;
			align-items: flex-start;
			align-content: flex-start;
			color: #333;

			.pic {
				width: 70rpx;
				height: 70rpx;
				border-radius: 50%;
			}

			.content {
				padding: 10rpx 15rpx;
				border-radius: 4px;
				max-width: 590rpx;
				word-break: break-all;
				line-height: 52rpx;
				position: relative;
			}

			/* 收到的消息 */
			&.pull {
				.content {
					margin-left: 20rpx;
					background-color: #f5f6f8;
					border: 1px solid #e7e8ea;
					// &::after {
					// 	content: '';
					// 	display: block;
					// 	width: 0;
					// 	height: 0;
					// 	border-top: 16rpx solid transparent;
					// 	border-bottom: 16rpx solid transparent;
					// 	border-right: 20rpx solid #fff;
					// 	position: absolute;
					// 	top: 16rpx;
					// 	left: -18rpx;
					// }
				}
			}

			/* 发出的消息 */
			&.push {
				/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
				flex-direction: row-reverse;

				.content {
					margin-right: 20rpx;
					background-color: #e6f7ff;
					border: 1px solid #223850;

					// &::after {
					// 	content: '';
					// 	display: block;
					// 	width: 0;
					// 	height: 0;
					// 	border-top: 16rpx solid transparent;
					// 	border-bottom: 16rpx solid transparent;
					// 	border-left: 20rpx solid #a0e959;
					// 	position: absolute;
					// 	top: 16rpx;
					// 	right: -18rpx;
					// }
				}
			}
		}
	}

	.flex_col {
		display: flex;
	}

	.enterbox {
		width: 100%;
		height: 20vh;
		position: relative;
		border-top: 1px solid #ccc;
		border-radius: 20rpx;
		padding: 30rpx;

		textarea {
			width: 100%;
			height: 100%;
			color: #333;
			padding-right: 10rpx;
		}

		.send {
			position: absolute;
			bottom: 30rpx;
			right: 30rpx;
			width: 160rpx;
			height: 90rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 30rpx;
			color: #fff;
			background-color: #f22d2d;
			cursor: pointer;
			border-radius: 20rpx;
		}
	}


	.updown {
		position: absolute;
		right: 230rpx;
		bottom: 60rpx;
	}


	.changeVoice {
		font-size: 26rpx;
		margin-top: 10rpx;
		cursor: pointer;
		color: #de4849;
	}
</style>